<?php

namespace app\app\controller;

use app\app\model\BiddingModel;
use app\BaseController;
use think\db\exception\DbException;
use think\facade\Db;

class Bidding extends BaseController
{
    private $model;

    /**
     * initialize
     * @return void
     */
    public function initialize()
    {
        $this->model = BiddingModel::class;
    }

    /**
     * C&U
     * @return void
     */
    public function save()
    {
        $id = input('id', '');
        $param = $this->request->param();

        if (empty($id)) {
            $model = new $this->model();
        } else {
            $model = $this->model::where('id', $id);
        }

        $model->save($param);

        $this->success('success');
    }

    /**
     * R
     * @return void
     * @throws DbException
     */
    public function list()
    {
        $where = [];

        $page_size = input('pageSize', '20');

        $data = $this->model::alias('a')
            ->leftJoin('sys_file_info b', 'a.file_id = b.file_id')
            ->where($where)
            ->field('a.*, b.file_path')
            ->paginate($page_size);

        empty($data) && $this->error('查询为空');
        $data = $data->toArray();
        empty($data['data']) && $this->error('未找到符合条件的数据');

        foreach ($data['data'] as $k => $v) {
            switch ($v['id']) {
                case 1:
                case 2:
                case 4:
                    $tmp = Db::table('t_bidding_gov_material')
                        ->where('bidding_id', $v['id'])
                        ->where('start_time', '>', date('Y-m-d H:i:s'))
                        ->order('start_time', 'asc')
                        ->find();
                    if (!empty($tmp)) {
                        $data['data'][$k]['start_time'] = $tmp['start_time'];
                    } else {
                        $data['data'][$k]['start_time'] = '暂无';
                    }

                    break;
                case 3:
                    $tmp = Db::table('t_bidding_province')
                        ->where('bidding_id', $v['id'])
                        ->where('declare_start_time', '>', date('Y-m-d H:i:s'))
                        ->order('declare_start_time', 'asc')
                        ->find();
                    if (!empty($tmp)) {
                        $data['data'][$k]['start_time'] = $tmp['declare_start_time'];
                    } else {
                        $data['data'][$k]['start_time'] = '暂无';
                    }

                    break;
                default:
                    $data['data'][$k]['start_time'] = '暂无';
            }
        }

        $this->success('success', $data);
    }

    /**
     * D
     * @return void
     * @throws DbException
     */
    public function del($id = 0)
    {
        !$id && $this->error('请传入id');

        $this->model::where('id', $id)->delete();

        $this->success('success');
    }
}